package com.demo.mockito;

import com.fasterxml.jackson.databind.JsonNode;
import lombok.SneakyThrows;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opensearch.client.opensearch.OpenSearchClient;
import org.opensearch.client.opensearch._types.aggregations.Aggregate;
import org.opensearch.client.opensearch._types.aggregations.Buckets;
import org.opensearch.client.opensearch._types.aggregations.LongTermsAggregate;
import org.opensearch.client.opensearch._types.aggregations.LongTermsBucket;
import org.opensearch.client.opensearch.core.SearchRequest;
import org.opensearch.client.opensearch.core.SearchResponse;

import java.util.List;
import java.util.Map;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class MockitoTest {

    /* 带泛型的参数使用注解mock, 取代mock() */
    @Mock
    SearchResponse<JsonNode> searchResponse;
    @Mock
    Map<String, Aggregate> aggMap;
    @Mock
    Buckets<LongTermsBucket> buckets;

    public MockitoTest() {
        MockitoAnnotations.openMocks(this);
    }

    @BeforeEach
    public void prepare() {
        when(searchResponse.aggregations()).thenReturn(aggMap);
        Aggregate aggregate = mock(Aggregate.class);
        when(aggMap.get("campaign_count")).thenReturn(aggregate);
        LongTermsAggregate longTermsAggregate = mock(LongTermsAggregate.class);
        when(aggregate.lterms()).thenReturn(longTermsAggregate);
        when(longTermsAggregate.buckets()).thenReturn(buckets);
        List<LongTermsBucket> bucketList = List.of(
                LongTermsBucket.of(b -> b.key("computer").docCount(5)),
                LongTermsBucket.of(b -> b.key("phone").docCount(10)));
        when(buckets.array()).thenReturn(bucketList);
    }

    @SneakyThrows
    @Test
    public void searchTest() {
        OpenSearchClient searchClient = mock(OpenSearchClient.class);
        SearchRequest request = mock(SearchRequest.class);
        when(searchClient.search(request, JsonNode.class)).thenReturn(searchResponse);

        SearchResponse<JsonNode> response = searchClient.search(request, JsonNode.class);
        List<LongTermsBucket> bucketsList = response.aggregations().get("campaign_count").lterms().buckets().array();
        Assertions.assertEquals(2, bucketsList.size());
    }

}
